#cs
# Redmine auto create users tool
# Author: ThuanLe
# Email: thuanle@cse.hcmut.edu.vn thuanle.cse@gmail.com
#ce

#include <IE.au3>
#include <Excel.au3>
#include <MsgBoxConstants.au3>
#include <Array.au3>
#include <FileConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>

#cs
# GUI Create for easily input
#ce
Opt("GUIOnEventMode",1)


Const $sTitle = "Auto Redmine User Creator v1.0 20140226"
Const $sAuthor = "ThuanLe@cse.hcmut.edu.vn"
Const $sWelcomeMessage = $sTitle & @CRLF & " by " & $sAuthor
Const $sSucceed = "Done"
Const $sDuplicated = "Duplicated"
Const $sFailed = "Failed"

$iUsernameText = -1
$iPasswordText = -1
$iRedmineURLText = -1
$iAccountInfoTxt = -1
$iLogEdit = -1

CreateGUI()

Func main($sRedmineAdminUser, $sRedmineAdminPass, $sRedmineURL, $sExcelFilePath)
   Local $sRedmineLoginURL = $sRedmineURL & "/login"
   Local $sRedmineCreateUserURL = $sRedmineURL & "/users/new"

   #cs
   # Parse the Excel to get data
   #ce
   Local $oExcel = _ExcelBookOpen($sExcelFilePath)
   If @error = 1 Then
	  LogMessage ("Error! Unable to create excel object")
	  Return
   ElseIf @error = 2 Then
	  LogMessage ("Error! File does not exist.")
	  Return
   EndIf

   Local $aSheet = _ExcelReadSheetToArray($oExcel)

   Local $iRowCount = UBound($aSheet,1)
   Local $iColCount = UBound($aSheet,2)

   If $iColCount < 5 Then
	  LogMessage ("Error! Excel file damaged. Number of columns = " & $iColCount)
	  Return
	EndIf

   Local $oIE = RedmineLogin($sRedmineLoginURL,$sRedmineAdminUser,$sRedmineAdminPass)

   Local $iSuccessfulCount = 0;
   Local $iDuplicatedCount = 0;
   Local $iFailedCount = 0;

   ; Parse Excel File and create users
   For $i = 2 To $iRowCount-1
	  Local $sMSSV = $aSheet[$i][1]
	  Local $sLastName = $aSheet[$i][2]
	  Local $sFirstName = $aSheet[$i][3]
	  Local $sEmail = $aSheet[$i][4]
	  Local $sPass = $aSheet[$i][5]
	  Local $sDone = ""
	  If $iColCount > 6 Then
		 $sDone = $aSheet[$i][6]
	  EndIf

	  If ($sDone <> $sSucceed) Then
		 Local $sResult = RedmineRegister($oIE,$sRedmineCreateUserURL,$sMSSV, $sLastName, $sFirstName, $sEmail, $sPass)
		 If ($sResult == $sSucceed) Then
			$iSuccessfulCount = $iSuccessfulCount + 1
		 ElseIf ($sResult == $sDuplicated) Then
			$iDuplicatedCount = $iDuplicatedCount + 1
		 Else
			$iFailedCount = $iFailedCount + 1
		 EndIf

		 LogMessage($sMSSV & " " & $sLastName & " " & $sFirstName &  " " & $sEmail & " " & $sPass & " " & $sResult)
		 _ExcelWriteCell($oExcel,$sResult,$i,6)
	  EndIf
   Next

   LogMessage("")
   LogMessage($iSuccessfulCount & " successful, " & $iDuplicatedCount & " duplicated, " & $iFailedCount & " failed.")
   _ExcelBookClose($oExcel)
EndFunc


Func RedmineLogin($sRedmineLoginURL,$sRedmineAdminUser,$sRedmineAdminPass)
    ;Login
   Local $oIE = _IECreate($sRedmineLoginURL)
   _IELoadWait($oIE)
   Local $oForm = _IEFormGetCollection($oIE,0)
   Local $oUsername = _IEFormElementGetObjByName($oForm, "username")
   Local $oPassword = _IEFormElementGetObjByName($oForm, "password")
   _IEFormElementSetValue($oUsername,$sRedmineAdminUser)
   _IEFormElementSetValue($oPassword,$sRedmineAdminPass)
   _IEFormSubmit($oForm)
   return $oIE
EndFunc


Func RedmineRegister($oIE,$sRedmineCreateUserURL,$sUserLogin, $sUserLastname, $sUserFirstname, $sUserMail, $sUserPass)
   ;Create new user
   _IENavigate($oIE,$sRedmineCreateUserURL)
   _IELoadWait($oIE)

   Local $oForm = _IEFormGetCollection($oIE,1)

   Local $oLogin = _IEFormElementGetObjByName($oForm, "user[login]")
   Local $oFirstname = _IEFormElementGetObjByName($oForm, "user[firstname]")
   Local $oLastName = _IEFormElementGetObjByName($oForm, "user[lastname]")
   Local $oMail = _IEFormElementGetObjByName($oForm, "user[mail]")
   Local $oPass = _IEFormElementGetObjByName($oForm, "user[password]")
   Local $oPassConfirmation = _IEFormElementGetObjByName($oForm, "user[password_confirmation]")

   _IEFormElementSetValue($oLogin,$sUserLogin)
   _IEFormElementSetValue($oFirstname,$sUserFirstname)
   _IEFormElementSetValue($oLastName,$sUserLastname)
   _IEFormElementSetValue($oMail,$sUserMail)
   _IEFormElementCheckBoxSelect($oForm,"1") ;senddiffmail; id = user_custom_field_values_1
   _IEFormElementSetValue($oPass,$sUserPass)
   _IEFormElementSetValue($oPassConfirmation,$sUserPass)

   ;submit
   _IEFormSubmit($oForm)
   _IELoadWait($oIE)

   Local $sWebContent = _IEBodyReadText($oIE)
   If StringInStr($sWebContent,"Successful creation.")  Then
	  Return $sSucceed
   ElseIf StringInStr($sWebContent,"Login has already been taken")  Then
	  Return $sDuplicated
   Else
	  Return $sFailed
   EndIf
EndFunc


#cs ###############################################################################################
# GUI Create for easily input
#ce ###############################################################################################
Func CreateGUI()
   Local $hMainGUI = GUICreate($sTitle, 320,470)
   GUISetOnEvent($GUI_EVENT_CLOSE,"CLOSEButton")
   GUICtrlCreateLabel("Username",10,10,100,20,$SS_CENTERIMAGE)
   $iUsernameText = GUICtrlCreateInput("admin", 110,10,200,20,$SS_CENTERIMAGE)

   GUICtrlCreateLabel("Password",10,40,100,20,$SS_CENTERIMAGE)
   $iPasswordText = GUICtrlCreateInput("password", 110,40,200,20,$SS_CENTERIMAGE)

   GUICtrlCreateLabel("Accounts info",10,70,100,20,$SS_CENTERIMAGE)
   $iAccountInfoTxt = GUICtrlCreateInput("a.xls", 110,70, 175, 20,$SS_CENTERIMAGE)
   Local $iAccountInfoBtn = GUICtrlCreateButton("...",290,70,20,20)
   GUICtrlSetOnEvent($iAccountInfoBtn,"AccountInfoBtn_click")

   GUICtrlCreateLabel("Redmine URL",10,100,100,20,$SS_CENTERIMAGE)
   $iRedmineURLText = GUICtrlCreateInput("http://cse.hcmut.edu.vn/rm2", 110,100, 200,20,$SS_CENTERIMAGE)

   Local $iGOButton = GUICtrlCreateButton("Go", 135,130,50)
   GUICtrlSetOnEvent($iGOButton, "GoBtn_click")

   $iLogEdit = GUICtrlCreateEdit("",10,160,300,300)

   GUISetState(@SW_SHOW)

   LogMessage($sWelcomeMessage)

   While 1
	  Sleep(100)
   WEnd
EndFunc

Func AccountInfoBtn_click()
   Local $sFileName = FileOpenDialog("Open",@WorkingDir & "\","Excel (*.xls;*.xlsx)",$FD_FILEMUSTEXIST)
   GUICtrlSetData($iAccountInfoTxt,$sFileName)
   LogMessage("Open file " & $sFileName)
EndFunc

Func GoBtn_click()
   LogMessage("Start.")
   Local $sRedmineAdminUser = GUICtrlRead($iUsernameText)
   Local $sRedmineAdminPass = GUICtrlRead($iPasswordText)
   Local $sRedmineURL = GUICtrlRead($iRedmineURLText)
   Local $sExcelFilePath = GUICtrlRead($iAccountInfoTxt)
   main($sRedmineAdminUser, $sRedmineAdminPass, $sRedmineURL, $sExcelFilePath)
   LogMessage("Done. Press Esc to exit.")
   MsgBox(0,$sTitle,"Done.")
EndFunc

Func CLOSEButton()
   Exit
EndFunc

Func LogMessage($sMessage)
   $sOldMessage = GUICtrlRead($iLogEdit)
   GUICtrlSetData($iLogEdit, $sOldMessage & $sMessage & @CRLF)
EndFunc
